<template>
    <div id="doQuestionPage">
        <a-card >
            <h1>{{ app.appName }}</h1>
            <p>{{ app.appDesc }}</p>
            <h2 style="margin-bottom: 16px">
                {{ current }}、{{ currentQuestion?.title }}
            </h2>
            <div>
                <a-radio-group
                        direction="vertical"
                        v-model="currentAnswer"
                        :options="currentQuestionOptions"
                        @change="doRadioChange"
                />
            </div>
            <div style="margin-top: 24px">
                <a-space size="large">
                    <a-button
                            type="primary"
                            circle
                            v-if="current < questionContent.length"
                            :disabled="!currentAnswer"
                            @click="current += 1"
                    >
                        下一题
                    </a-button>
                    <a-button
                            type="primary"
                            v-if="current === questionContent.length"
                            circle
                            :loading="submitting"
                            :disabled="!currentAnswer"
                            @click="doSubmit"
                    >
                        {{ submitting ? "评分中" : "查看结果" }}
                    </a-button>
                    <a-button v-if="current > 1" circle @click="current -= 1">
                        上一题
                    </a-button>
                </a-space>
            </div>
        </a-card>
<!--        <a-empty v-if="currentQuestion === []"  description="创建人未设置题目"/>-->

        <a-result v-if="questionContent === []" title="This is title content" subtitle="This is subtitle content">
            <template #extra>
                <a-space>
                    <a-button type="primary">Back</a-button>
                </a-space>
            </template>
        </a-result>
    </div>
</template>

<script setup lang="ts">
    import {reactive, ref, watchEffect, computed} from 'vue';
    import {userLoginUsingPost} from "@/api/userController";
    import {useLoginUserStore} from "@/store/userStore";
    import message from "@arco-design/web-vue/es/message"
    import {useRouter} from "vue-router";
    import {createAppUsingPost, editAppUsingPost, getAppByIdUsingGet} from "@/api/appController";
    import {APPTYPE_MAP, SCORINGTYPE_MAP} from '@/constant/enum';
    import {
        createQuestionUsingPost,
        editQuestionUsingPost,
        getQuestionVoByIdUsingGet,
        listQuestionVoByPageUsingPost
    } from "@/api/questionController";
    import {addUserAnswerUsingPost, generateUserAnswerIdUsingGet} from "@/api/userAnswerController";

    const loginUserStore = useLoginUserStore();
    const router = useRouter();
    const submitting = ref(false);


    //题目内容结构（理解为题目列表）
    const questionContent = ref<API.QuestionContentDTO[]>([]);

    //当前app的信息
    const app = ref<API.AppVO>({});

    //当前题目序号
    const current = ref(1);

    //当前题目
    const currentQuestion = ref<API.QuestionContentDTO>({});

    //当前题目选项
    const currentQuestionOptions = computed(() => {
        //如果当前题目的选项存在就遍历,否则返回空数组
        return currentQuestion.value?.options ?
            currentQuestion.value.options.map((option) => {
                return {label: `${option.key}.${option.value}`, value: option.key}
            }) : []
    })
    //当前用户选择的答案
    const currentAnswer = ref<string>();
    //回答列表
    const answerList = reactive<string[]>([]);

    //获取前页面跳转过来的参数
    interface Props {
        appId: string
    }

    const props = withDefaults(defineProps<Props>(), {
        appId: () => {
            return "";
        }
    })

    //调用后端接口获取id（幂等性操作）
    const id = ref<number>();
    const generateId = async () =>{
        const res = await generateUserAnswerIdUsingGet();
        if (res.data.code === 0 && res.data.data) {
            id.value = res.data.data;
        } else {
            message.error("获取id，" + res.data.message);
        }
    }



    /**
     * 加载数据（获取题目）
     */
    const loadData = async () => {
        if (!props.appId) {
            return;
        }
        //获取App
        let res: any = await getAppByIdUsingGet({
            id: props.appId as any
        });
        if (res.data.code === 0 && res.data.data) {
            app.value = res.data.data;
        } else {
            message.error("获取应用失败，" + res.data.message);
        }

        //定义一个判断应用是否存在的变量
        const isHaveQuestion = ref(true);

        //获取题目
        res = await listQuestionVoByPageUsingPost({
            appId: props.appId as any,
            current: 1,
            pageSize: 1,
            sortField: "createTime",
            sortOrder: "descend",
        });
        if (res.data.code === 0 && res.data.data?.records) {
            if (res.data.data?.records === []) {
                questionContent.value = [];
            } else{
                questionContent.value = res.data.data.records[0]?.questionContent;
            }

        } else {
            message.error("获取题目失败，" + res.data.message);
        }
    };

    //提交按钮
    const doSubmit = async () => {
        if (!props.appId || !questionContent.value) {
            return;
        }
        submitting.value = true;
        const res = await addUserAnswerUsingPost({
            id:id.value,
            appId: props.appId as any,
            choices: answerList
        });
        if (res.data.code === 0 && res.data.data) {
            message.success("操作成功,即将跳转结果页面")
            setTimeout(() => {
                router.push({
                    path: `/answer/result/${res.data.data}`,
                })
            }, 3000)

        } else {
            message.error("操作失败" + res.data.message);
        }
        submitting.value = false;
    };


    /**
     * 监听 searchParams 变量，改变时触发数据的重新加载
     */
    watchEffect(() => {
        loadData()
    })

    watchEffect(() => {
        //current.value - 1：是因为current的默认值为1，题目中索引从0开始，所以要减1
        if(questionContent.value != []){
            currentQuestion.value = questionContent.value[current.value - 1]
        }
        currentAnswer.value = answerList[current.value - 1];
    })

    /**
     * 选中选项后，保存选项记录
     * @param value
     */
    const doRadioChange = (value: string) => {
        answerList[current.value - 1] = value;
    };

    //页面加载的时候获取到id（幂等性操作）
    watchEffect(() =>{
        generateId();
    })

</script>